import tkinter as tk
from tkinter import messagebox
import pickle

window=tk.Tk()
window.title('Welcome to Python')
window.geometry('450x300')

#user information
tk.Label(window,text='User name:').place(x=50,y=150)
tk.Label(window,text='Password:').place(x=50,y=190)

var_username=tk.StringVar()
var_username.set('admin')
var_pwd=tk.StringVar()
var_pwd.set('admin')

entry_usrname=tk.Entry(window,textvariable=var_username)
entry_pwd=tk.Entry(window,textvariable=var_pwd,show='*')
entry_usrname.place(x=160,y=150)
entry_pwd.place(x=160,y=190)


def user_login():
    user_name=var_username.get()
    user_pwd=var_pwd.get()
    try:                               
        with open('users_info.pickle','rb') as user_file:         #如果有就读取数据
            users_info=pickle.load(user_file)
    except FileNotFoundError:
        with open('users_info.pickle','wb') as user_file:           #如果没有就保存数据
            users_info={'admin':'admin'}
            pickle.dump(users_info,user_file)

    if user_name in users_info:                                 #如果 读取到的数据里有 用户名
        if user_pwd==users_info[0]:
            tk.messagebox.showinfo(title='Welcome',message='how are you ?'+user_name)
        else:
            tk.messagebox.showinfo(message='Error,your Password is wrong,try again')
    else:
        is_sign_up=tk.messagebox.askyesno(message='Welcome you have not sign up yet,Sign up today?')
        if is_sign_up:
            user_sign_up()        
    
def user_sign_up():
    #建立 子窗口
    window_sign_up=tk.Toplevel(window)
    window_sign_up.geometry('350x200')
    window_sign_up.title('sign up window')

    new_name=tk.StringVar()
    new_name.set('admin')
    tk.Label(window_sign_up,text='User name:').place(x=10,y=10)
    entry_new_name=tk.Entry(window_sign_up,textvariable=new_name)
    entry_new_name.place(x=150,y=10)

    new_pwd=tk.StringVar()
    tk.Label(window_sign_up,text='Password:').place(x=10,y=50)
    entry_new_pwd=tk.Entry(window_sign_up,textvariable=new_pwd)
    entry_new_pwd.place(x=150,y=50)

    new_pwd_confirm=tk.StringVar()
    tk.Label(window_sign_up,text='Password confrim:').place(x=10,y=90)
    entry_new_pwd_confirm=tk.Entry(window_sign_up,textvariable=new_pwd_confirm)
    entry_new_pwd_confirm.place(x=150,y=90)

btn_login=tk.Button(window,text='Login',command=user_login)
btn_login.place(x=170,y=230)
btn_sign=tk.Button(window,text='Sign Up',command=user_sign_up)
btn_sign.place(x=270,y=230)

window.mainloop()

